/*
 * @Date: 2024-03-27 09:23:07
 * @Author: LiSong
 * @LastEditors: g05047
 * @LastEditTime: 2024-08-27 15:36:13
 * @Description: 文件的通用操作hook
 */
import FileUtils,{fileType} from '@/utils/file-utils.js';

import { useFilesApi, useFilesZjpsApi } from '@/api';
import { RkConfirmBox } from '@/components/message-box';
import { ElLoading, ElMessage } from 'element-plus';


/**
 * 通用的文件操作
 */
export const useFileOptation = () => {

  /**
   * 删除文件的通用方法
   *
   * @param {String} fileId 文件ID
   * @returns new Promise
   */
  const fileDelete = (fileId) => {
    return new Promise((resolve, reject) => {
      RkConfirmBox({
        content: `您确定要删除吗？`,
        onSubmit: () => {
          const loading = ElLoading.service({ lock: true, text: '处理中......'  });
          useFilesApi().delUploadFileData(fileId).then(res => {
            if (res.code === 200) {
              ElMessage.success('删除成功！')
              resolve(res)
            } else {
              ElMessage.error(res.msg ?? '业务失败！')
            }
          }).finally(() => {
            loading.close()
          });
        }
      })
    })
  }

  /**
   * 预览文件的通用方法
   * 
   * @param {String} fileId 文件ID
   * @param {String} fileName 文件名称
   * @returns 
   */
  const filePreview = async(fileId, fileName, isOnline) => {
    const fileSuffix = FileUtils.getFileSuffix(fileName)
    if (!FileUtils.isSupportPreview(fileSuffix)) {
      ElMessage.warning('暂不支持文件预览，请下载后查看！')
      return
    }
    const loading = ElLoading.service({ lock: true, text: '加载中......' });
    try {
      const result = await useFilesApi().previewFileData(fileId);
      if (result && result.code) {
        ElMessage.error(result.msg ?? '业务失败！')
      } else {
        if (result) {
          const type = FileUtils.getPreviewFileType(fileSuffix)
          const blobUrl = FileUtils.convertBlobURL(result, type);
          FileUtils.openNewWindow(blobUrl, fileName, isOnline, fileSuffix);
        } else {
          ElMessage.warning('没有任何数据！')
        }
      }
      loading.close()
    } catch(err) {
      loading.close()
      console.error('attachment file preview error', err)
    }
  }

  /**
   * 评审文件预览
   * 
   * @param {Object} param {
   *  taskId-任务ID
   *  applyId-申报ID
   *  expertId-评审ID
   * }
   */
  const filePreviewByReview = async (params, fileName='项目评审报告') => {
    const loading = ElLoading.service({ lock: true, text: '加载中......' });
    try {
      const result = await useFilesZjpsApi().onlineReviewData(params)
      if (result && result.size) {
        const fileSuffix = FileUtils.getFileSuffixByType(result.type)
        if (!FileUtils.isSupportPreview(fileSuffix)) {
          ElMessage.warning('暂不支持文件预览，请下载后查看！')
          loading.close()
          return
        }
        const type = FileUtils.getPreviewFileType(fileSuffix)
        const blobUrl = FileUtils.convertBlobURL(result, type);
        FileUtils.openNewWindow(blobUrl, fileName, false, fileSuffix);
      } else {
        ElMessage.warning('没有任何数据！')
      }
      loading.close()
    } catch (err) {
      loading.close()
      console.error('file preview error', err)
    }
  }

  /**
   * 下载文件的通用方法
   * 
   * @param {String} fileId 文件ID
   * @param {String} fileName 文件名称
   * @returns 
   */
  const fileDownload = async(fileId, fileName) => {
    const loading = ElLoading.service({ lock: true, text: '文件正在下载，请稍后......' });
    try {
      const result = await useFilesApi().downloadFileData(fileId);
      if (result && result.code) {
        ElMessage.error(result.msg ?? '业务失败！')
      } else {
        if (result) {
          FileUtils.dowloadFile(result, fileName);
        } else {
          ElMessage.warning('没有任何数据！')
        }
      }
      loading.close();
    } catch (err) {
      console.error('attachment file download error', err)
      loading.close();
    }
  }

  /**
   * 评审文件下载
   * 
   * @param {Object} param {
   *  taskId-任务ID
   *  applyId-申报ID
   *  expertId-评审ID
   * }
   */
  const fileDownloadByReview = async(params, fileName) => {
    const loading = ElLoading.service({ lock: true, text: '文件正在下载，请稍后......' });
    try {
      const result = await useFilesZjpsApi().downloadReviewFileByBlob(params)
      const blobData = result.data
      if (blobData.type === 'application/json') {
        const blobText = JSON.parse(await blobData.text())
        if (blobText && blobText.code) {
          ElMessage.error(blobText.msg ?? '业务失败！')
          loading.close()
          return
        }
      }
      if (blobData && blobData.size > 0) {
        FileUtils.dowloadFileByStream(result, fileName);
      } else {
        ElMessage.warning('没有任何数据，请确认')
      }
      loading.close();
    } catch(err) {
      loading.close();
      console.error('file download error', err)
    }
  }
  
  /**
   *
   * 
   * @param {Object} param {
   *  proId-任务ID
   *  expertId-评审ID
   * }
   */
  const fileDownloadByPdf= async(params, fileName) => {
    const loading = ElLoading.service({ lock: true, text: '文件正在下载，请稍后......' });
    try {
      const result = await useFilesZjpsApi().downloadProPdfByBlob(params)
      console.log('fileDownloadByReview', result)
      const blobData = result.data
      if (blobData.type === 'application/json') {
        const blobText = JSON.parse(await blobData.text())
        if (blobText && blobText.code) {
          ElMessage.error(blobText.msg ?? '业务失败！')
          loading.close()
          return
        }
      }
      if (blobData && blobData.size > 0) {
        FileUtils.dowloadFileByStream(result, fileName);
      } else {
        ElMessage.warning('没有任何数据，请确认')
      }
      loading.close();
    } catch(err) {
      loading.close();
      console.error('file download error', err)
    }
  }

  return {
    fileDelete,
    filePreview,
    fileDownload,
    filePreviewByReview,
    fileDownloadByReview,
    fileDownloadByPdf
  }

}